package com.jy.rhin.application.registration;

import cn.org.chiss.rhin._2015.base.Boolean;
import cn.org.chiss.rhin._2015.base.*;
import cn.org.chiss.rhin._2015.base.object.*;
import cn.org.chiss.rhin._2015.registration.person.*;
import com.jy.api.misc.MiscAPI;
import com.jy.api.misc.dto.QuHuaDMDto;
import com.jy.api.patient.PatientAPI;
import com.jy.api.patient.dto.BingRenXXDto;
import com.jy.framework.base.entity.Page;
import com.jy.framework.base.utils.DateUtil;
import com.jy.framework.base.utils.Serializer;
import com.jy.rhin.application.assembler.PersonInfoAssembler;
import com.jy.rhin.config.RhinFaultSubCode;
import com.jy.rhin.facade.ws.basic.wsEntry.exception.RhinWSException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.Integer;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PersonService {

    @Autowired
    private PatientAPI patientAPI;
    @Autowired
    private MiscAPI miscAPI;


    public PersonRecordFeedResponse zhuCe(PersonRecordFeed message) {
//        Patient personInfo = message.getPersonInfo();
        BingRenXXDto bingRenXXDto = PersonInfoAssembler.toBingRenXXDto(message);
        //患者注册码如果有的话则是更新
        MainID mainID;
        if ( (mainID = message.getPersonInfo().getId()) != null) {
            bingRenXXDto.setId(mainID.getValue());
        }
        bingRenXXDto.setAppId(message.getPersonInfo().getIdentifier().get(0).getSystem().getValue());
        bingRenXXDto.setEid(String.valueOf(message.getPersonInfo().getIdentifier().get(0).getValue()));
        String bingRenId = patientAPI.insertOrUpdate(bingRenXXDto);
//        FeignServiceClient.execute(patientAPI::insertOrUpdate, bingRenXXDto, "插入或更新");
        if (bingRenId == null) {
            throw new RhinWSException(RhinFaultSubCode.PatientNotFoundFault);
        }
        PersonRecordFeedResponse personRecordFeedResponse = new PersonRecordFeedResponse();
        MainID2 id = new MainID2();
        id.setValue(new cn.org.chiss.rhin._2015.base.String().setValue(bingRenId));
        id.setSystem(new cn.org.chiss.rhin._2015.base.String().setValue( "1"));
//        id.setValue(String.valueOf(bingRenId));
        personRecordFeedResponse.setMasterIdentifer(id);

        return personRecordFeedResponse;
    }


    public PersonRecordQueryResponse personRecordQuery(PersonRecordQuery personMessage) {
        String hyzk = null;
        String swbj = null;
        String qscsrq = null;
        String zzcsrq = null;
        String xbdm = null;
        if(personMessage.getAdhocQuery() !=null && !ObjectUtils.isEmpty(personMessage.getAdhocQuery().getSlot())){
            for(Slot s : personMessage.getAdhocQuery().getSlot()){
                if("$maritalStatus".equals(s.getName().getValue())){
                    hyzk = s.getValueList().getValue().get(0).getValue();
                }
                if("$deceasedInd".equals(s.getName().getValue())){
                    swbj = s.getValueList().getValue().get(0).getValue();
                }
                if("$birthTimeFrom".equals(s.getName().getValue())){
                    qscsrq = s.getValueList().getValue().get(0).getValue();
                }
                if("$birthTimeTo".equals(s.getName().getValue())){
                    zzcsrq = s.getValueList().getValue().get(0).getValue();
                }
                if("$gender".equals(s.getName().getValue())){
                    xbdm = s.getValueList().getValue().get(0).getValue();
                }
            }
        }
        Integer from = personMessage.getFrom().getValue();
        Integer maxCount = personMessage.getMaxCount().getValue();
        Page<BingRenXXDto> page = patientAPI.pageHLHTJMList(hyzk,swbj, qscsrq, zzcsrq, xbdm,  from, maxCount).getData();
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            throw new RhinWSException(RhinFaultSubCode.PatientNotFoundFault);
        }
        log.debug("互联互通剧名接口 info:{}", Serializer.serialize(page));
        return personPageToPractitionerQueryResponse(page,personMessage);
    }

    public PersonIdentifierQueryResponse personIdentifierQuery(PersonIdentifierQuery personIdentifierMessage) {
        String appId = null;
        String eid = personIdentifierMessage.getIdentifier().getValue().getValue();
        if(personIdentifierMessage.getIdentifier().getSystem()!=null){
            appId = personIdentifierMessage.getIdentifier().getSystem().getValue();
        }
        if(StringUtils.isEmpty(eid) || "?".equals(eid)){
            throw new RhinWSException(RhinFaultSubCode.PatientNotFoundFault);
        }
        List<BingRenXXDto> bingRenXXDtoList = patientAPI.getHLHTJMJCSYList(eid,appId).getData();
        if (CollectionUtils.isEmpty(bingRenXXDtoList)) {
            throw new RhinWSException(RhinFaultSubCode.PatientNotFoundFault);
        }
        return personIdentifierQueryResponse(bingRenXXDtoList,personIdentifierMessage);
    }

    private PersonRecordQueryResponse personPageToPractitionerQueryResponse(Page<BingRenXXDto> page ,PersonRecordQuery personMessage){
        PersonRecordQueryResponse resp = new PersonRecordQueryResponse();
        resp.setFrom(personMessage.getFrom());
        resp.setCount(personMessage.getMaxCount());
        cn.org.chiss.rhin._2015.base.Integer total = new cn.org.chiss.rhin._2015.base.Integer();
        total.setValue(0);
        resp.setTotalCount(total);
        if(page !=null){
            total.setValue((int)page.getTotal());
            resp.setTotalCount(total);
            if(!ObjectUtils.isEmpty(page.getRecords())){
                List<Patient> patientList = new ArrayList<Patient>();
                for(BingRenXXDto z:page.getRecords()){
                    Patient p = new Patient();
                    MainID mainID = new MainID();
                    mainID.setValue(z.getEmpi());
                    mainID.setSystem("");
                    p.setId(mainID);
                    p.setIdentifier(getList(Identifier.class, new Identifier().setValue(new ID().setValue("his123")).setSystem(new URI().setValue("his1234"))));
                    p.setTelecom(new Telecom().setValue(new cn.org.chiss.rhin._2015.base.String().setValue(z.getShouJiHao())));
                    p.setAddress(new Address().setText(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJiaTingDZ()))
                            .setState(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSFDM()))
                            .setCity(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSDM()))
                            .setDistrict(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDQDM()))
                            .setTown(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDJDDM()))
                            .setStreet(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSQDM())));
                    Person person = new Person();
                    MainID mainID1 =new MainID();
                    mainID1.setValue(z.getEmpi());
                    mainID1.setSystem("");
                    person.setId(mainID1);
//                    person.setName(getList(HumanName.class,new HumanName().setText(new cn.org.chiss.rhin._2015.base.String().setValue(z.getBingRenXM()))));
                    person.setName(getList(HumanName.class,new HumanName().setValue(z.getBingRenXM())));
                    p.setAssignedPerson(person);
                    java.lang.Boolean b = new java.lang.Boolean(false);
                    if( "1".equals(z.getBingRenZT()) ){
                        b=  java.lang.Boolean.TRUE;
                    }
                    p.setAssignedPerson((Person) new Person()
                            .setName(getList(HumanName.class,new HumanName().setValue(z.getBingRenXM())))
                            .setBirthTime(new cn.org.chiss.rhin._2015.base.Date().setValue(z.getChuShengRQ()!=null?z.getChuShengRQ().replaceAll("-","")+"223000":""))
                            .setGender(new Code().setValue(z.getXingBieDM()))
                            .setAddress(getList(Address.class,new Address().setText(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJiaTingDZ()))
                                    .setState(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSFDM()))
                                    .setCity(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSDM()))
                                    .setDistrict(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDQDM()))
                                    .setTown(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDJDDM()))
                                    .setStreet(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSQDM()))))
                            .setTelecom(getList(Telecom.class,new Telecom().setValue(new cn.org.chiss.rhin._2015.base.String().setValue(z.getShouJiHao()))))
                            .setBirthPlace(new Address().setText(new cn.org.chiss.rhin._2015.base.String().setValue(z.getChuShengDi()))
                                    .setState(new cn.org.chiss.rhin._2015.base.String().setValue(z.getChuShengDSFDM()))
                                    .setCity(new cn.org.chiss.rhin._2015.base.String().setValue(z.getChuShengDSDM()))
                                    .setDistrict(new cn.org.chiss.rhin._2015.base.String().setValue(getXZQHMC(z.getJuZhuDQDM())))
                                    .setTown(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDJDDM()))
                                    .setStreet(new cn.org.chiss.rhin._2015.base.String().setValue(z.getJuZhuDSQDM())))
                            .setMaritalStatusCode(new Code().setValue(z.getHunYinZT()))
                            .setDeceasedInd(new Boolean()
                                    .setValue(b))
//                            .setDeceasedTime(new cn.org.chiss.rhin._2015.base.DateTime().setValue(DateUtil.getYYMMDDHHMMSS(z.getGengXinSJ())))
                            .setDeceasedTime(b?new cn.org.chiss.rhin._2015.base.DateTime().setValue(DateUtil.getYYMMDDHHMMSS(z.getGengXinSJ())): null)
                            .setId(mainID1));
//                    p.setContact(getList(Contact.class,new Contact()));
                    //p.setGuardian();
                    p.setStatusCode(new ObjectStatus().setValue(ObjectStatusPrimitive.ACTIVE));
                    patientList.add(p);
                }
                resp.setPersonInfo(patientList);
            }

        }
        return resp;
    }

    private PersonIdentifierQueryResponse personIdentifierQueryResponse(List<BingRenXXDto> bingRenXXDtoList ,PersonIdentifierQuery personIdentifierMessage){
        PersonIdentifierQueryResponse resp = new PersonIdentifierQueryResponse();
        List<Identifier> personIdentifer= new ArrayList<>();
            if(!ObjectUtils.isEmpty(bingRenXXDtoList)) {
                for (BingRenXXDto z : bingRenXXDtoList) {
                    Identifier p = new Identifier();
                    p.setValue(new ID().setValue(z.getEid()));
                    p.setSystem(new URI().setValue(z.getAppId()));
                    personIdentifer.add(p);
                }
            }
        resp.setPersonIdentifer(personIdentifer);
        return resp;
    }


    private String getXZQHMC(String xzqhdm){
        if(xzqhdm==null||"".equals(xzqhdm)){
            return null;
        }
        QuHuaDMDto data = miscAPI.getQuHuaDMByDM(xzqhdm).getData();
        if (data == null) {
            return null;
        }
        return data.getMingCheng();
    }



    private <T>  List<T> getList(Class<T> c,T b){
        ArrayList<T> list = new ArrayList<T>();
        list.add(b);
        return list;
    }


}
